import React from 'react';
import {Form, Input, Button, Select, Table, Card, Modal, Popover, Pagination, Message, Icon, Spin } from 'antd';
import FinanceModal from '../../../components/financeModal/finance';
const FormItem = Form.Item;
const Option = Select.Option;

let List = React.createClass({

  contextTypes: {
    router: React.PropTypes.object
  },

  getInitialState() {
    let current = this.props.location.state  ? this.props.location.state.currentPage : 1
    return {
      visible: false,
      data: [],
      formsData: {},
      financeVisible: false,
      dataBox: null,
      total: 0,
      currentPage: current,
      pageSize: 12

    }
  },

  componentDidMount() {
    this.handleSearch();
  },

  handlePageChange(current) {
   this.listRender(current);
  },

  listRender(current){
    let forms = this.props.form.getFieldsValue();
    let param = Object.assign({}, forms, {currentPage:current});
    this.setState({
      currentPage:current
    });
    this.fetch(param);
  },
  fetch(param) {
    let params = Object.assign({}, {pageSize: this.state.pageSize, currentPage: 1}, param)
    let _me = this
    Utils.sendAjax({
      url: '/tenement/contract/list',
      data: JSON.stringify(params),
      callback: function(result) {
        if (result.code == '200') {
          _me.setState({
            data: result.data,
            dataBox: _me.renderBox(result.data),
            loading: false,
              total: result.page.total

          })
        } else {
          Message.error(result.message, 10)
        }
      }
    })
  },

  renderBox(data) {
    if (!data[0]) {
      return (
        <li className="none-data">
          <span><Icon type="frown" />暂无数据...</span>
        </li>
      )
    }
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    let boxArr = [];
    data.forEach( (item) => {
      let decorateMap = {
        '1': '毛坯',
        '2': '简装',
        '3': '豪华'
      }
      let payMap = {
        '2': '即将付款',
        '1': '已付款',
        '-1': '未付款'
      }
      let content = (
        <Form horizontal className="form-wrap-li">
          <FormItem {...formItemLayout}
            label="业主姓名">
            <p className="ant-form-text" >{item.ownerName}</p>
          </FormItem>
          <FormItem {...formItemLayout}
            label="房屋地址">
            <p className="ant-form-text" >{item.address}</p>
          </FormItem>
          <FormItem {...formItemLayout}
            label="物业名称">
            <p className="ant-form-text" >{item.tenementName}</p>
          </FormItem>
          <FormItem {...formItemLayout}
            label="联系电话">
            <p className="ant-form-text" >{item.mobilePhone}</p>
          </FormItem>
          { item.payStatus ?
          <FormItem {...formItemLayout}
            label="装修类型">
            <p className="ant-form-text" >{decorateMap[item.decorate]}</p>
          </FormItem> : null}
          { item.payStatus ?
          <FormItem {...formItemLayout}
            label="房屋面积">
            <p className="ant-form-text" >{item.area}平方米</p>
          </FormItem> : null}
          {
            item.type === 'own' ? '':
            <div>
              <FormItem {...formItemLayout}
                label="房屋租金">
                <p className="ant-form-text" >{item.rent}元/月</p>
              </FormItem>
              <FormItem {...formItemLayout}
                label="起租日期">
                <p className="ant-form-text" >{item.startTime}</p>
              </FormItem>
              { item.payStatus ?
              <FormItem {...formItemLayout}
                label="结束日期">
                <p className="ant-form-text" >{item.expireTime}</p>
              </FormItem> : null}
              <FormItem {...formItemLayout}
                label="租赁期限">
                <p className="ant-form-text" >{item.contractPeriod}个月</p>
              </FormItem>
            </div>
          }
          
          <FormItem >
            <Button type="ghost" size="small" onClick={this.handleModify.bind(this, item)}>修改</Button>
            {
              item.type === 'own' ? '':
              <span>
                <Button type="ghost" size="small" onClick={this.handlePay.bind(this, item)} disabled={ item.payStatus ? false : true}>交费</Button>
                <Button type="ghost" size="small" onClick={this.handleContract.bind(this, item)} disabled={ item.payStatus ? false : true}>终止合约</Button>
                <Button type="ghost" size="small" onClick={this.handleHistory.bind(this, item)} disabled={ item.payStatus ? false : true}>费用历史</Button>
              </span>
            }
            
          </FormItem>
        </Form>
      );
      let boxDom = (
        <li className="ul-wrap-li" key={`item-${item.tenementId}`}>
          <Popover placement="right" title="房源信息" content={content} trigger="click" overlayStyle={{zIndex:100}} >
            <Card >
              <p><span className="">{item.ownerName}</span><span className="li-tel"><Icon type="mobile" /><em>{item.mobilePhone}</em></span>
                { item.tenementContractId !== 0 ?
                  <span
                    className={`status ${ item.contractStatus == 1 ? 'color1' : 'color2'}`}>{item.contractStatus == 1 ? '正常' : '逾期'}</span>
                  : null}
                { item.tenementContractId !== 0 ?
                  <span
                    className={`pay ${ item.payStatus == 1 ? 'color1' : 'color2'}`}>{payMap[item.payStatus]}</span>
                    : <span className="editor-span" onClick={this.handleModify.bind(this, item)}><Icon type="edit" />完善信息</span>
                }
              </p>
              {item.isBorrow === 2 ?
                <div>
                  {
                    item.type === 'own' ? 
                    <p><strong>房源自有</strong></p>:
                    <p>
                      <strong>￥{item.rent ? item.rent.toFixed(2): '0.00'}</strong>
                    </p>
                  }
                  
                  <p>
                    {item.address}
                  </p>
                </div>
                :
                <div>
                  {
                    item.type === 'own' ? 
                    <p><strong>房源自有</strong></p>:
                    <p>
                      <strong>￥{item.rent ? item.rent.toFixed(2): '0.00'}</strong>{item.tenementContractId !== 0 && item.isBorrow === 1 ? <span className="loanIcon"  >融</span>:''}
                    </p>
                  }
                  
                  <p>
                    {item.address} {item.tenementContractId !== 0 && item.isBorrow !== 1 ? <Button className="loanFincail" type="ghost" size="small" onClick={this.willFinancing.bind(this, item)}>我要融资</Button>: null}
                  </p>
                </div>
              }
              {
                item.type === 'own' ? 
                <p className="ant-form-item ant-wrap-time"><span className="ant-p"></span></p>:
                <p className="ant-form-item ant-wrap-time">
                  <span className="ant-p"><label htmlFor="st">应交租日：</label><span id="st">{item.nextTime ? item.nextTime : '- -'}</span></span>
                </p>
              }
              
            </Card>
          </Popover>
        </li>
      )
      boxArr.push(boxDom)
    })
    return boxArr;
  },

  setModalVisible(item) {
    this.setState({
      financeVisible: true,
      visible: false,
      tenementId: item.tenementId
    });
  },

  willFinancing(item, e) {
    e.stopPropagation()
    let _me = this;
    console.log(item)
    let tenementId = item.tenementId;
    Utils.sendAjax({
      url: '/loan/apply/check',
      data: JSON.stringify({tenementId: tenementId, type: 102}),
      callback: (result)=> {
        if(result.code == '200') {
          _me.setModalVisible(item)
        }else{
          Message.error(result.message, 10)
        }
      }
    })

  },
  handleModify(record) {
    let params = {
      tenementContractId: record.tenementContractId,
      tenementId: record.tenementId,
      currentPage: this.state.currentPage
    };
    let goPathUrl= '/landlord/houseResource/update';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },

  handlePay(record) {
    let params = {
      tenementContractId: record.tenementContractId,
      tenementId: record.tenementId,
       currentPage: this.state.currentPage
    };
    let goPathUrl= '/landlord/houseResource/pay';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },

  handleContract(record) {
    let params = {
      tenementContractId: record.tenementContractId,
      tenementId: record.tenementId,
      payStatus: record.payStatus,
       currentPage: this.state.currentPage
    };

    console.log(params)
    let goPathUrl= '/landlord/houseResource/contract';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },

  handleHistory(record) {
    let params = {
      tenementContractId: record.tenementContractId,
      tenementId: record.tenementId,
       currentPage: this.state.currentPage
    };
    let goPathUrl= '/landlord/houseResource/history';
    this.context.router.push({pathname: goPathUrl, state: {...params}});
  },

  handleSearch() {
    this.listRender(this.state.data.length !==0 ? this.state.currentPage : 1);
  },

  handleReset() {
    this.props.form.resetFields();
  },

  handleCancel() {
    this.setState({
      visible: false,
      financeVisible: false,
    });
  },

  render () {

    const { getFieldProps } = this.props.form;

    const financeChild = {
      financeVisible: this.state.financeVisible,
      tenementId: this.state.tenementId,
      financeType: '102', // 装修贷
      callBack: this.handleCancel,
    };

    console.log(this.state.tenementId)

    return (
      <div>
        <div className="search-bar">
          <Form inline>
            <FormItem  label="业主姓名">
              <Input {...getFieldProps('ownerName') } placeholder="业主姓名"/>
            </FormItem>
            <FormItem label="联系电话">
              <Input {...getFieldProps('mobilePhone')} placeholder="联系电话"/>
            </FormItem>
            <FormItem label="物业名称">
              <Input {...getFieldProps('tenementName')} placeholder="物业名称"/>
            </FormItem>
              <FormItem label="租赁期限">
              <Input {...getFieldProps('contractPeriod')} placeholder="租赁期限"/>
            </FormItem>
            <FormItem label="支付状态">
              <Select defaultValue="1" {...getFieldProps('payStatus', {initialValue: ''}) } style={{width: 162}}>
                <Option value="">全部</Option>
                <Option value="1">已支付</Option>
                <Option value="2">即将支付</Option>
                <Option value="-1">未支付</Option>
              </Select>
            </FormItem>
            <FormItem>
              <Button type="primary" onClick={this.handleSearch} style={{marginRight: 20}}>查询</Button>
              <Button type="default" onClick={this.handleReset} >重置</Button>
            </FormItem>
          </Form>
        </div>
        <Spin tip="正在加载数据..." spinning={this.state.loading}>
          <ul className="ul-show-card">
            {this.state.dataBox}
          </ul>
        </Spin>
        {this.state.data[0] ?
        <div className="box-page">
          <Pagination onChange={this.handlePageChange}
                      current={this.state.currentPage} total={this.state.total} pageSize={this.state.pageSize} />
        </div> : null}
        <FinanceModal {...financeChild} />
      </div>
    );
  }
});
List = Form.create()(List);
export default List